/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  ZhiShiDetailActivity.java   
 * @Package com.jiyi.activity.main   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-28 上午10:31:16   
 * @version V1.0     
 */
package com.jiyi.activity.main;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html.ImageGetter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.inteface.ShareInteface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.SharePopView;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.maintenance.wxapi.WeChatWebBean;
import com.swift.utils.GlideUtil;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX.Req;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ZhiShiDetailActivity extends ActivityBase implements ShareInteface {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.tvZhiShiTitle)
	TextView tvZhiShiTitle;
	@BindView(R.id.tvZhiShiDate)
	TextView tvZhiShiDate;
	@BindView(R.id.tvZhiShiSourch)
	TextView tvZhiShiSourch;
	@BindView(R.id.tvZhiShiReadNum)
	TextView tvZhiShiReadNum;
	@BindView(R.id.tvContent)
	TextView tvContent;
	@BindView(R.id.tvZhiShiPraiseNum)
	TextView tvZhiShiPraiseNum;
	@BindView(R.id.ivCover)
	ImageView ivCover;

	String type,id;
	SharePopView mSharePopView;
	BaseUiListener mBaseUiListener;
	Tencent mTencent;
	private IWXAPI api;
	private WeChatWebBean wcwb;
	NewsBean newsBean;
	//加载圈
	Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhishi_detail);
		ButterKnife.bind(this);
		init();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-28
	 */
	private void init() {
		getIntentData();
		setTop();
		getData();
//		setData();
		mSharePopView = new SharePopView(this, this);
		mBaseUiListener = new BaseUiListener();
		// 注册QQ分享
		mTencent = Tencent.createInstance("1106178877",
				this.getApplicationContext());
		// 注册微信分享
		api = WXAPIFactory.createWXAPI(this, AppConfig.APP_ID);
		api.registerApp(AppConfig.APP_ID);
	}

	/**   
	 * @author: HYM 
	 * @Title: getData   
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void 
	 * @date: 2017-7-21
	 */  
	private void getData() {
		String url = "";
		if (type.equals("zhishi")) {
			url = WebApi.MAIN_ZHISHI_DETAIL;
		}
		else {
			url = WebApi.MAIN_ZIXUN_DETAIL;
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);

		VolleyRequest.StringRequestPost(getContext(), url, "",
				params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								NewsBean temp = new Gson().fromJson(data, NewsBean.class);
								setNews(temp);
//								if (type.equals("zhishi")) {
//									EventBus.getDefault().post(new ZhiShiListEvent(ZhiShiListEvent.MAIN_ZHISHI_FRAGMENT));
//								}
//								else {
//									EventBus.getDefault().post(new ZiXunListEvent(ZiXunListEvent.MAIN_ZIXUN_FRAGMENT));
//								}
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}


	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-28
	 */
	private void getIntentData() {
		id = getIntent().getStringExtra("id");
		type = getIntent().getStringExtra("type").isEmpty() ? "zhishi"
				: getIntent().getStringExtra("type");
	}

	/**
	 * @author: HYM
	 * @Title: setTop
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-28
	 */
	private void setTop() {
		tvBack.setText("");
		tvTitle.setText(type.equals("zhishi") ? "涨姿势" : "资讯");
		Drawable searchDraw = getResources().getDrawable(
				R.mipmap.icon_share_normal);
		searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),
				searchDraw.getMinimumHeight());
		tvSearch.setCompoundDrawables(searchDraw, null, null, null);
		tvSearch.setText("");
	}

	@OnClick({ R.id.tvSearch, R.id.tvBack,R.id.tvZhiShiPraiseNum })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			mSharePopView.showPopWindow();
			break;
		case R.id.tvZhiShiPraiseNum:
			praise(id);
			break;
		default:
			break;
		}
	}

	Context getContext() {
		return this;
	}

	ImageGetter imgGetter = new ImageGetter() {
		public Drawable getDrawable(String source) {
			Drawable drawable = null;
			URL url;
			try {
				url = new URL(source);
				drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
			} catch (Exception e) {
				return null;
			}
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			return drawable;
		}
	};

	/**
	 * <p>
	 * Title: onShareFriend
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see ShareInteface#onShareFriend()
	 */
	@Override
	public void onShareFriend() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: onShareGroup
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see ShareInteface#onShareGroup()
	 */
	@Override
	public void onShareGroup() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: onShareWXGroup
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see ShareInteface#onShareWXGroup()
	 */
	@Override
	public void onShareWXGroup() {
		// 分享到微信朋友圈
		wcwb = new WeChatWebBean();
		wcwb.setWebpageUrl(newsBean.getReference_url());
		wcwb.setTitle(newsBean.getTitle().length()>100?newsBean.getTitle().substring(0, 100):newsBean.getTitle());
		wcwb.setDescription(newsBean.getContent().length()>200?newsBean.getContent().substring(0, 200):newsBean.getContent());
		wcwb.setThumb(R.mipmap.ic_launcher);
		wcwb.setScene(Req.WXSceneTimeline);
		wcwb.send(api, getApplicationContext());
	}

	/**
	 * <p>
	 * Title: onShareWXFriend
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see ShareInteface#onShareWXFriend()
	 */
	@Override
	public void onShareWXFriend() {
		// 分享到微信好友
		wcwb = new WeChatWebBean();
		wcwb.setWebpageUrl(newsBean.getReference_url());
		wcwb.setTitle(newsBean.getTitle().length()>500?newsBean.getTitle().substring(0, 500):newsBean.getTitle());
		wcwb.setDescription(newsBean.getContent().length()>1000?newsBean.getContent().substring(0, 1000):newsBean.getContent());
		wcwb.setThumb(R.mipmap.ic_launcher);
		wcwb.setScene(Req.WXSceneSession);
		wcwb.send(api, getApplicationContext());
	}

	/**
	 * <p>
	 * Title: onShareQQ
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see ShareInteface#onShareQQ()
	 */
	@Override
	public void onShareQQ() {
		// onClickAppShare();
		onClickShare();
	}

	/**
	 * <p>
	 * Title: onShareWB
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see ShareInteface#onShareWB()
	 */
	@Override
	public void onShareWB() {
		// TODO Auto-generated method stub

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (null != mTencent)
			mTencent.onActivityResult(requestCode, resultCode, data);
	}

	private class BaseUiListener implements IUiListener {

		@Override
		public void onCancel() {
			Log.e("onCancel  ", "onCancel");
		}

		@Override
		public void onComplete(Object arg0) {
			Log.e("onComplete  ", "onComplete");
		}

		@Override
		public void onError(UiError arg0) {
			Log.e("onError  ", "onError");
		}
	}


	private void onClickShare() {
		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TITLE, newsBean.getTitle());
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, newsBean.getContent());
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
				TextUtils.isEmpty(newsBean.getReference_url())?"http://www.baidu.com":newsBean.getReference_url());
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
				newsBean.getImage());
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "吉消宝");
		mTencent.shareToQQ(this, params, mBaseUiListener);
	}

	void praise(String id) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		VolleyRequest.StringRequestPost(this, WebApi.ZIXUN_PRAISE, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								JSONObject dataJson = new JSONObject(data);
								String praiseNum = dataJson.getString("likeNum");
								tvZhiShiPraiseNum.setText(praiseNum);
								Drawable praiseDrawable = getResources().getDrawable(
										R.mipmap.icon_praise_on);
								praiseDrawable.setBounds(0, 0, praiseDrawable.getMinimumWidth(),
										praiseDrawable.getMinimumHeight());
								tvZhiShiPraiseNum.setCompoundDrawables(praiseDrawable, null, null, null);
								tvZhiShiPraiseNum.setEnabled(false);
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
	
	/**   
	 * @author: HYM 
	 * @Title: setNews   
	 * @Description: TODO(填充数据)   
	 * @param newsBean void 
	 * @date: 2017-7-21
	 */  
	void setNews(NewsBean newsBean)
	{
		this.newsBean = newsBean;
		tvZhiShiTitle.setText(newsBean.getTitle());
		tvZhiShiDate.setText(newsBean.getCreate_time());
		tvZhiShiReadNum.setText(newsBean.getReading()+"");
		tvZhiShiPraiseNum.setText(newsBean.getLikenum()+"");
		tvZhiShiSourch.setText("来源："+newsBean.getAuthor());
		tvContent.setText(newsBean.getContent());
		if (!TextUtils.isEmpty(newsBean.getImage())) {
			ivCover.setVisibility(View.VISIBLE);
			GlideUtil.load(this, newsBean.getImage(), ivCover);
		}
		
	}
}
